package tools

import config._
import org.apache.commons.math3.stat.StatUtils
import play.api.libs.json.Json

object Violin extends MyFile  {

  def Run(path: String) = {
    try {
      val matrix = s"$path/matrix.txt"
      val row = matrix.readLines.map(_.split("\t").tail).transpose.map(x => x.head -> x.tail.map(_.toDouble).toArray).toSeq
      val boxPlot = drawBox(row)
      Json.obj("state" -> 0, "boxPlot" -> boxPlot)
    } catch {
      case e: Exception => Json.obj("state" -> 1, "msg" -> e.getMessage)
    }
  }

  def drawBox(row: Seq[(String, Array[Double])]) = {
    val data = row.map { case (name, values) =>
      val minValue = values.min
      val Q1 = StatUtils.percentile(values, 25)
      val Q2 = StatUtils.percentile(values, 50)
      val Q3 = StatUtils.percentile(values, 75)
      val maxValue = values.max
      (name, Array(minValue, Q1, Q2, Q3, maxValue))
    }
    Json.obj("categories" -> data.map(_._1), "values" -> data.map(_._2))
  }


}

